<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
      <el-form-item label="渠道名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="渠道名称"></el-input>
      </el-form-item>
      <el-form-item label="渠道推广码" prop="code">
        <el-input v-model="dataForm.code" :disabled="dataForm.id ? true : false" placeholder="渠道推广码"></el-input>
      </el-form-item>
      <el-form-item label="是否打开" prop="openFlag">
        <ren-select v-model="dataForm.openFlag" dict-type="yes_no" placeholder="是否打开"></ren-select>
      </el-form-item>
      <el-form-item prop="intervalList" label="客服列表">
        <el-button type="primary" plain :icon="Plus" style="margin-bottom: 20px" @click="addRateHandle"> 新增 </el-button>
        <el-table :data="customerServiceList" border size="small">
          <el-table-column prop="initVal" label="客服名称" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.name" placeholder="请输入客服名称" />
            </template>
          </el-table-column>
          <el-table-column label="账号" align="center">
            <template #header>
              <el-tooltip class="box-item" effect="dark" content="注意：What'sApp客服只需要填写手机号码,telegram客服需要填写完整链接地址" placement="top-start">
                <div style="display: flex; justify-content: center; align-items: center">
                  <span style="margin-right: 3px">账号 </span> <el-icon><Warning /></el-icon>
                </div>
              </el-tooltip>
            </template>
            <template #default="scope">
              <el-input v-model="scope.row.value" placeholder="请输入账号或者链接" />
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" width="180">
            <template #default="scope">
              <el-switch v-model="scope.row.remark" inline-prompt active-text="启用" :active-value="1" :inactive-value="0" inactive-text="停用" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100">
            <template #default="scope">
              <el-button type="danger" size="small" :plain="true" @click="removeRateHandle(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
import { Plus, Warning } from "@element-plus/icons-vue";

const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const customerServiceList = ref([]);

const dataForm = reactive({
  id: "",
  name: "",
  code: "",
  openFlag: 1,
  extData: []
});

const validateCode = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error(t("validate.required")));
  }
  // 校验是否为6位数字
  const pattern = /^\d{6}$/;
  if (value && !pattern.test(value)) {
    return callback(new Error("渠道码应为6位数字"));
  }
  callback();
};
const rules = ref({
  name: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  code: [{ required: true, validator: validateCode, trigger: "blur" }]
});

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (id) {
    getInfo(id);
  }
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/member/memberpromochannel/" + id).then((res:any) => {
    Object.assign(dataForm, res.data);
    if (res.data.extData) {
      customerServiceList.value = JSON.parse(res.data.extData);
    }
  });
};

// 添加条件
const addRateHandle = async () => {
  let serviceList: any = customerServiceList.value || [];
  let data = {
    name: "",
    value: "",
    remark: 1
  };
  serviceList.push(data);
};

// 删除条件
const removeRateHandle = async (index: any) => {
  let intervalList: any = customerServiceList.value;
  intervalList.splice(index, 1);
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    let formData: any = {
      ...dataForm
    };
    if (customerServiceList.value) {
      formData.extData = JSON.stringify(customerServiceList.value);
    }
    (!dataForm.id ? baseService.post : baseService.put)("/member/memberpromochannel", formData).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>
